package com.chexiehui.jc.ui.activity;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;

import com.aries.ui.view.radius.RadiusRelativeLayout;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.AppApplication;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseActivity;
import com.chexiehui.jc.event.ChooseHistoryTagEvent;
import com.chexiehui.jc.event.SearchHistoryEvent;
import com.chexiehui.jc.event.SoftKeyboardShowOrHideEvent;
import com.chexiehui.jc.model.SearchHistory;
import com.chexiehui.jc.realm.SearchHistoryDao;
import com.chexiehui.jc.ui.fragment.SearchHomeFragment;
import com.chexiehui.jc.ui.fragment.SearchResultFragment;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.utils.SoftKeyboardFixerForFullscreen;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Date;

import butterknife.BindView;

public class SearchActivity extends BaseActivity {

    @BindView(R.id.fl_search_page)
    FrameLayout fl_search_page;
    private RadiusRelativeLayout rrl_search_panel;
    private EditText et_search_content;
    private int pageTag = 0;

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void setTitleBar() {
        View centerAction = View.inflate(mContext, R.layout.layout_title_action_search, null);
        rrl_search_panel = centerAction.findViewById(R.id.rrl_search_panel);
        et_search_content = centerAction.findViewById(R.id.et_search_content);
        titleBar.addCenterAction(titleBar.new ViewAction(centerAction))
                .setRightText("搜索")
                .setOnLeftTextClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        if(pageTag != 0){
                            transactionHomePage();
                        }else{
                           onBackPressed();
                        }
                    }
                })
                .setOnRightTextClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        if(pageTag == 0){
                            if(StringUtils.isTrimEmpty(et_search_content.getText().toString().trim())){
                                showToast("请输入关键字搜索");
                            }else{
                                addSearchHistory(et_search_content.getText().toString().trim());
                                transactionResultPage(et_search_content.getText().toString().trim());
                            }
                        }else{
                            transactionHomePage();
                        }
                    }
                });
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView(Bundle var1) {
        SoftKeyboardFixerForFullscreen.assistActivity(this);
        et_search_content.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                if (!StringUtils.isTrimEmpty(et_search_content.getText().toString().trim())) {
                    addSearchHistory(et_search_content.getText().toString().trim());
                    transactionResultPage(et_search_content.getText().toString().trim());
                }else{
                    showToast("请输入关键字搜索");
                }
                return true;
            }
            return false;
        });
        transactionHomePage();
    }

    private void addSearchHistory(String key) {
        long count = AppApplication.getInstances().getSearchHistoryDao()
                .queryBuilder().where(SearchHistoryDao.Properties.Name.eq(key))
                .count();
        if(count <= 0){
            SearchHistory searchHistory = new SearchHistory();
            searchHistory.setCreateTime(new Date());
            searchHistory.setName(key);
            AppApplication.getInstances().getSearchHistoryDao().insert(searchHistory);
            EventBus.getDefault().post(new SearchHistoryEvent());
        }
    }

    private void transactionHomePage(){
        pageTag = 0;
        titleBar.setRightText("搜索");
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.fl_search_page, SearchHomeFragment.getInstance());
        transaction.commit();
    }

    private void transactionResultPage(String keyword){
        pageTag = 1;
        titleBar.setRightText("取消");
        KeyboardUtils.hideSoftInput(mContext);
        rrl_search_panel.requestFocus();
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.fl_search_page, SearchResultFragment.getInstance(keyword));
        transaction.commit();
    }

    @Subscribe
    public void onSoftKeyboardShowOrHideEvent(SoftKeyboardShowOrHideEvent event){
        //软键盘弹出 回到搜索页
        if(event.getState() == 1){
            if(pageTag != 0){
                transactionHomePage();
            }
        }
    }

    @Subscribe
    public void onChooseHistoryTagEvent(ChooseHistoryTagEvent event){
        if(!StringUtils.isTrimEmpty(event.getKeyword())){
            transactionResultPage(event.getKeyword());
        }
    }
}
